//
//  FRQDeviceSoftwareViewController.m
//  FRQBluetoothKit_Example
//
//  Created by admin on 2023/10/25.
//  Copyright © 2023 xuchunhai. All rights reserved.
//

#import "FRQDeviceSoftwareViewController.h"
#import "DeviceSoftwareViews.h"
#import "FRQNoBluetoothYetViewController.h"
//#import <FRQBluetoothKit/FRQBluetoothManager.h>

@interface FRQDeviceSoftwareViewController ()<FRQBluetoothManagerDelegate,FRQBImageOrVersionDelegte>
@property (nonatomic,strong) CBPeripheral *MyPeripheral;
@property (nonatomic,assign) Boolean isContect;
@property (nonatomic,assign) NSInteger version;
@property (nonatomic,strong) DeviceSoftwareViews *DeviceSoftwareView;
@property (nonatomic,strong) NSString *updateFilePath;
@end

@implementation FRQDeviceSoftwareViewController
- (DeviceSoftwareViews *)DeviceSoftwareView{
    if (nil==_DeviceSoftwareView) {
        _DeviceSoftwareView=skXibView(@"DeviceSoftwareViews");
        [self.view addSubview:_DeviceSoftwareView];
        [_DeviceSoftwareView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuide);
            make.bottom.mas_equalTo(self.mas_bottomLayoutGuide);
            make.right.left.mas_equalTo(0);
        }];
//        _DeviceSoftwareView.txtVersion.text=[NSString stringWithFormat:@"  %@",skDevice.binVersion.length>0?@"":skDevice.binVersion];
        
        @weakify(self)
        [[_DeviceSoftwareView.btnUpdates rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
//            NSString *otaBinDataPath = [[NSBundle mainBundle] pathForResource:@"ble_simple_peripheral_ota" ofType:@"bin"];
//            NSData *otaBinData = [NSData dataWithContentsOfFile:otaBinDataPath];
//            [[FRQBluetoothManager shareManager] updateOTAWithData:otaBinData toPeripheral:self.MyPeripheral];
            //蓝牙11.30  重点 现在是本地文件  要传输网络文件 替换data
//            NSString *otaBinDataPath = [[NSBundle mainBundle] pathForResource:@"jyble_sdk" ofType:@"bin"];
//            NSData *otaBinData = [NSData dataWithContentsOfFile:otaBinDataPath];
//            [[FRQBluetoothManager shareManager] updateOTAWithData:otaBinData toPeripheral:self.MyPeripheral];
            
            _DeviceSoftwareView.btnUpdates.enabled=NO;
            NSString *homeDir = NSHomeDirectory();
            [PKNetTools downloadWithURL:self.updateFilePath fileDir:homeDir progress:^(NSProgress * _Nonnull progress) {
                
            } callback:^(NSString * _Nonnull path, NSError * _Nonnull error) {
                //开始OTA升级
                NSString *fileUrl=[[path componentsSeparatedByString:@":///"] lastObject];
                
                NSData *otaBinData = [NSData dataWithContentsOfFile:fileUrl];
                [APP startTimer];
                [[FRQBluetoothManager shareManager] updateOTAWithData:otaBinData toPeripheral:self.MyPeripheral];
                if(error){
                    _DeviceSoftwareView.btnUpdates.enabled=YES;
                }
            }];
            
            
            
        }];
    }
    return _DeviceSoftwareView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.DeviceSoftwareView.hidden=NO;
    // Do any additional setup after loading the view.
//    app/version/dev/bin
    NSLog(@"链接了哪个蓝牙%@",skDevice.devName);
    self.title=@"Device Software";
    ////蓝牙12.01
    [FRQBluetoothManager shareManager].imgDelegate = self;
    [FRQBluetoothManager shareManager].delegate = self;
    [[FRQBluetoothManager shareManager] writeThreeAndThreeDevice];
    _DeviceSoftwareView.txtVersion.enabled = NO;
}
//蓝牙11.30 版本号回调代理
- (void)onVersionNum:(NSInteger)version{
    self.version = version;
    CGFloat g = self.version/10.0;
    _DeviceSoftwareView.txtVersion.text=[NSString stringWithFormat:@"  %.1f",g];
    [self appVersionUpdate:version];
    
}
//蓝牙12.01
//检测升级
-(void)appVersionUpdate:(NSInteger)version{
    NSDictionary *dic=@{@"binVersion":[NSString stringWithFormat:@"%ld",version]};
 
    [skNetTools skGETWithURL:[NSString stringWithFormat:@"%@%@",skURL,@"/app/version/dev/bin"] parameters:dic cachePolicy:0 callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
        if(model.code==200){
            
            NSString *homeDir = NSHomeDirectory();
//            /var/mobile/Containers/Data/Application/53FCDEBD-57F7-4E2E-BEE0-49682605EE58
            NSDictionary *binUrl=model.data;
            self.updateFilePath=toString(binUrl[@"appUrl"]);
//            UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"tip" message:@"updata ota" preferredStyle:UIAlertControllerStyleAlert];
//
//            [alertCtrl addAction:[UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//            }]];
//            [alertCtrl addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//
//            }]];
//            [self presentViewController:alertCtrl animated:YES completion:^{
//
//            }];
        }else{
            [SkToast SkToastShow:model.msg];
            _DeviceSoftwareView.btnUpdates.enabled=NO;
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -- FRQBluetoothManagerDelegate
-(void)onBLEManagerCancelScan:(id<FRBleAbility>)ability{
    
    
}

-(void)onBLEManagerDiscoverPeripheral:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral advertisement:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    if([peripheral.name isEqualToString:skDevice.devName] && self.updateFilePath){
        
        [[FRQBluetoothManager shareManager] autoReconnectToPeripheral:peripheral];
    }
}

-(void)onBLEManagerConnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    
    if (error) {
//        MBProgressHUD *toastHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        toastHUD.mode = MBProgressHUDModeText;
//
//        toastHUD.label.text = [NSString stringWithFormat:@"蓝牙设备%@，连接失败<%@>！！",peripheral.name,error.localizedDescription];
//        [toastHUD hideAnimated:YES afterDelay:5.0];
    }
    else{
        self.isContect=YES;
        //蓝牙链接成功
        self.MyPeripheral=peripheral;
        NSLog(@"链接成功%@",peripheral);
        
        
    }
    
}

-(void)onBLEManagerStateChange:(id<FRBleAbility>)ability{
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
//    MBProgressHUD *toastHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    toastHud.mode = MBProgressHUDModeText;
    switch (ability.state) {
        case FRQManagerStateUnsupported:
        {
//            toastHud.label.text = @"请检查你蓝牙使用权限或检查设备问题";
        }
            break;
        case FRQManagerStateUnauthorized:
        {
//            toastHud.label.text = @"蓝牙设备暂无法使用，请在设置中授权";
        }
            break;
        case FRQManagerStatePoweredOff:
        {
//            toastHud.label.text =@"请打开蓝牙";
            [[FRQBluetoothManager shareManager] cancelScan];
        }
            break;
        case FRQManagerStatePoweredOn:
        {
//            toastHud.label.text = @"蓝牙已打开";
            //scan
            [[FRQBluetoothManager shareManager] scanPeripherals];
        }
            break;
        default:
            break;
    }
//    [toastHud hideAnimated:YES afterDelay:5.0];
    
}

-(void)onBLEManagerDisconnect:(id<FRBleAbility>)ability peripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
//
//    MBProgressHUD *toastHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    toastHUD.mode = MBProgressHUDModeText;
//    toastHUD.label.text = [NSString stringWithFormat:@"蓝牙设备%@已断开！！",peripheral.name];
//    if (error) { //异常断开设备连接
//        toastHUD.detailsLabel.text = error.localizedDescription;
//    }
//    [toastHUD hideAnimated:YES afterDelay:3.0];
    
}

// OTA升级阶段回调
-(void)onBLEManagerBeginUpdateOTA:(id<FRBleAbility>)ability{
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHUD.label.text = @"Ready to upgrade...";
    progressHUD.mode = MBProgressHUDModeText;
    [progressHUD hideAnimated:YES afterDelay:2.0];
    
}

-(void)onBLEManagerUpdateOTA:(id<FRBleAbility>)ability progress:(double)aProgress{
    
    MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
    if (!progressHUD) {
        progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    progressHUD.label.text = @"OTA is being upgraded...";
    progressHUD.detailsLabel.text = [NSString stringWithFormat:@"Current progress %.f %%, please wait...",aProgress];
    progressHUD.mode = MBProgressHUDModeAnnularDeterminate;
    progressHUD.progress = aProgress/100.0;
    
    if(aProgress == 100){
//        [MBProgressHUD hideHUDForView:self.view animated:NO];
//        //alert
//        NSString *alertMsg = error?error.localizedDescription:@"success";
//        UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"ware" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
//        [alertCtrl addAction:[UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//            
//        }]];
//        
//        [self presentViewController:alertCtrl animated:YES completion:^{}];

        self.updateFilePath = @"";
    }
}

-(void)onBLEManagerUpdateOTAFinish:(id<FRBleAbility>)ability error:(NSError *)error{
    
    _DeviceSoftwareView.btnUpdates.enabled = YES;
    
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    //alert
    NSString *alertMsg = error?error.localizedDescription:@"success";
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"ware" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
    [alertCtrl addAction:[UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[FRQBluetoothManager shareManager] closeAuotReconnectPeripheral:self.MyPeripheral];
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    
    [self presentViewController:alertCtrl animated:YES completion:^{}];
    
}

- (void)fRQCroppedAction{
    _DeviceSoftwareView.btnUpdates.enabled = YES;
//    [APP.window makeToast:@"Connection disconnected" duration:3.0];
    [MBProgressHUD hideHUDForView:self.view animated:NO];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[FRQBluetoothManager shareManager] cancelScan];
    //蓝牙12.01
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FRQCropped" object:nil];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //蓝牙12.01
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fRQCroppedAction) name:@"FRQCropped" object:nil];
}
@end
